const Router = require("koa-router");
const login = new Router();
const bodyparser = require('koa-bodyparser')
const db = require('../utils/db')

const jwt = require('jsonwebtoken')
const {token} = require("mysql/lib/protocol/Auth");

// 调用这个中间件 就可以拿到千吨啊post传过来的数据
login.use(bodyparser())
//写对应的接口
login.post('/register',async (ctx)=>{
    let myaccount = ctx.request.body.account;
    let mypwd = ctx.request.body.pwd;

    let searchSql = `select * from users where account = '${myaccount}'`;
    let myarr = await new Promise((resolve,reject)=>{
        return db.query(searchSql, (err,data)=>{
            if (err) throw err;
            resolve(data);
        })
    })
    if (myarr.length>0){
    //    证明有这个账号
        if (myarr[0].pwd == mypwd){
            ctx.body={
                msg: "注册成功",
                token:myarr[0].token,
                myaccount:myaccount
            }
        }else {
            ctx.body="密码错误";
        }

    }else {
        // 创建一个token
        let mytoken = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, 'secret', { expiresIn: 3600 });
        let insertsql = `insert into users (account,pwd,token) values ('${myaccount}','${mypwd}','${mytoken}')`;
        db.query(insertsql,(err, data)=>{
            if (err) throw err;
            console.log(data);
            ctx.body = {
                msg:"注册成功",
                token:mytoken,
                account: myaccount
            }
        })
    }
})



module.exports = login;